<template>
  <div class="edit-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="790px" destroy-on-close>
      <el-row :gutter="35" style="margin-top: 20px;">
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item prop="name" label="昵称">
            <el-input v-model="state.content.name" placeholder="请输入昵称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item prop="account" label="账号">
            <el-input v-model="state.content.account" placeholder="请输入账号" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item prop="password" label="密码">
            <el-input v-model="state.content.password" type="password" placeholder="请输入密码" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onSubmit" type="primary" size="default">确认</el-button>
          <el-button @click="onCancel" size="default">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { createAdminApi, updateAdminApi } from '@/api/admin';

const emit = defineEmits(['refresh']);

// 定义变量内容
const dialogFormRef = ref();

const useContent = () => {
  return {
    account: '',
    password: '',
    name: '',
    id: ''
  }
}

const state = reactive({
  content: {} as any,
  dialog: {
    isShowDialog: false,
    type: 0,
    title: '新增',
  },
});

// 打开弹窗
const openDialog = (type: string, row?: any) => {
  state.dialog.isShowDialog = true
  if (type === 'edit') {
    state.dialog.title = '编辑'
    state.dialog.type = 1
    state.content.account = row.account
    state.content.name = row.name
    state.content.id = row.id
  } else {
    state.dialog.type = 0
    state.content = useContent()
  }
};
// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
  state.content = useContent()
  emit('refresh');
};

// 取消
const onCancel = () => {
  closeDialog();
};

// 提交
const onSubmit = () => {
  if (state.dialog.type === 0) {
    createAdminApi(state.content).then(() => {
      onCancel()
      emit('refresh');
    });
  }
  else {
    updateAdminApi(state.content).then(() => {
      onCancel()
      emit('refresh');
    });
  }
};


defineExpose({
  openDialog,
});
</script>


<style scoped lang="scss">
:deep(.el-dialog__header) {
  margin: 0;
  border-bottom: 1px dashed rgba(0, 0, 0, .2);
}

:deep(.el-dialog__footer) {
  border-top: 1px dashed rgba(0, 0, 0, .2);
}
</style>